import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:ui';
import 'package:todo_project/services/notification_service.dart';
import 'pages/statistic.dart';
import 'pages/today_home.dart';
import 'pages/profile_page.dart'; // 导入个人资料页面
import 'models/task.dart'; // 添加Task模型导入
import 'pages/schedule_page.dart';
import 'theme/app_theme.dart';
import 'services/task_storage_service.dart';
import 'services/settings_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await NotificationService().init(); // 初始化通知服务
  SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
    statusBarIconBrightness: Brightness.dark,
  ));
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]).then((_) => runApp(const ToDoApp()));
}

class ToDoApp extends StatelessWidget {
  const ToDoApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ToDo App',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: const MaterialColor(0xFF6366F1, {
          50: Color(0xFFF0F9FF),
          100: Color(0xFFE0E7FF),
          200: Color(0xFFC7D2FE),
          300: Color(0xFFA5B4FC),
          400: Color(0xFF818CF8),
          500: Color(0xFF6366F1),
          600: Color(0xFF4F46E5),
          700: Color(0xFF4338CA),
          800: Color(0xFF3730A3),
          900: Color(0xFF312E81),
        }),
        scaffoldBackgroundColor: AppTheme.scaffoldColor,
        fontFamily: 'SF Pro Display',
        colorScheme: const ColorScheme.light(
          primary: AppTheme.primaryColor,
          secondary: AppTheme.secondaryColor,
          surface: AppTheme.cardColor,
          background: AppTheme.scaffoldColor,
          error: AppTheme.errorColor,
        ),
        appBarTheme: const AppBarTheme(
          backgroundColor: Colors.transparent,
          elevation: 0,
          systemOverlayStyle: SystemUiOverlayStyle.dark,
          titleTextStyle: TextStyle(
            color: AppTheme.textPrimaryColor,
            fontSize: AppTheme.fontSizeXXL,
            fontWeight: FontWeight.w600,
          ),
        ),
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            backgroundColor: AppTheme.primaryColor,
            foregroundColor: Colors.white,
            elevation: 0,
            padding: const EdgeInsets.symmetric(
              horizontal: AppTheme.paddingL,
              vertical: AppTheme.paddingM,
            ),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(AppTheme.radiusM),
            ),
          ),
        ),
        cardTheme: CardTheme(
          color: AppTheme.cardColor,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(AppTheme.radiusM),
          ),
          shadowColor: Colors.black.withOpacity(0.04),
        ),
      ),
      home: const MainPage(),
    );
  }
}

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> with TickerProviderStateMixin {
  int _currentIndex = 0;
  List<Task> _tasks = [];
  late AnimationController _navAnimationController;
  late AnimationController _iconAnimationController;
  late PageController _pageController;
  final TaskStorageService _storageService = TaskStorageService.instance;
  final NotificationService _notificationService = NotificationService();
  final SettingsService _settingsService = SettingsService();
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    
    // 初始化动画控制器
    _navAnimationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    
    _iconAnimationController = AnimationController(
      duration: const Duration(milliseconds: 200),
      vsync: this,
    );
    
    // 初始化页面控制器
    _pageController = PageController(initialPage: _currentIndex);
    
    // 加载数据
    _loadTasks();
    
    _navAnimationController.forward();
  }

  // 加载任务数据
  Future<void> _loadTasks() async {
    try {
      final loadedTasks = await _storageService.loadTasks();
      setState(() {
        if (loadedTasks.isEmpty) {
          // 如果没有保存的数据，添加示例任务
          _addSampleTasks();
        } else {
          _tasks = loadedTasks;
        }
        _isLoading = false;
      });
      print('数据加载完成：${_tasks.length} 个任务');
    } catch (e) {
      print('加载数据失败：$e');
      // 如果加载失败，添加示例任务
      setState(() {
        _addSampleTasks();
        _isLoading = false;
      });
    }
  }

  @override
  void dispose() {
    _navAnimationController.dispose();
    _iconAnimationController.dispose();
    _pageController.dispose();
    super.dispose();
  }

  void _addSampleTasks() {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    
    // 添加今日的示例任务
    _tasks.addAll([
      Task(
        id: '1',
        title: '晨间运动',
        time: DateTime(today.year, today.month, today.day, 7, 0),
        priority: 3,
        location: '健身房',
        category: 'Personal',
      ),
      Task(
        id: '2',
        title: '团队会议',
        time: DateTime(today.year, today.month, today.day, 9, 30),
        priority: 2,
        location: '办公室',
        category: 'Work',
        isCompleted: true,
        completedTime: DateTime(today.year, today.month, today.day, 10, 30),
      ),
      Task(
        id: '3',
        title: '项目评审',
        time: DateTime(today.year, today.month, today.day, 14, 0),
        priority: 3,
        location: '会议室A',
        category: 'Work',
      ),
      Task(
        id: '4',
        title: '购买生活用品',
        time: DateTime(today.year, today.month, today.day, 18, 0),
        priority: 1,
        location: '超市',
        category: 'Personal',
        isCompleted: true,
        completedTime: DateTime(today.year, today.month, today.day, 17, 30),
      ),
    ]);
  }

  void _onTaskUpdate(Task task) async {
    setState(() {
      final index = _tasks.indexWhere((t) => t.id == task.id);
      if (index != -1) {
        _tasks[index] = task;
      } else {
        _tasks.add(task);
      }
    });
    
    // 保存到本地存储
    try {
      await _storageService.saveTasks(_tasks);
      print('任务已保存：${task.title}');
    } catch (e) {
      print('保存任务失败：$e');
    }

    // 处理通知
    _handleTaskNotification(task);
  }

  void _onTaskDelete(Task task) {
    setState(() {
      _tasks.removeWhere((t) => t.id == task.id);
    });
    _storageService.saveTasks(_tasks);
    _notificationService.cancelNotificationForTask(task.id);
  }

  void _handleTaskNotification(Task task) async {
    final settings = await _settingsService.loadNotificationSettings();
    if (settings['enableAll'] && settings['taskReminders']) {
      if (task.isCompleted || task.isDeleted) {
        _notificationService.cancelNotificationForTask(task.id);
      } else {
        // 解析提醒时间
        final reminderTimeString = settings['reminderTime'] as String;
        final parts = reminderTimeString.split(' ');
        final value = int.parse(parts[0]);
        Duration reminderDuration;
        if (reminderTimeString.contains('分钟')) {
          reminderDuration = Duration(minutes: value);
        } else {
          reminderDuration = Duration(hours: value);
        }
        
        _notificationService.scheduleNotificationForTask(task, reminderDuration);
      }
    } else {
      // 如果禁用了通知，则取消
      _notificationService.cancelNotificationForTask(task.id);
    }
  }

  void _onTabTapped(int index) {
    if (index != _currentIndex) {
      setState(() {
        _currentIndex = index;
      });
      
      // 切换到对应页面
      _pageController.animateToPage(
        index,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
      
      // 播放图标动画
      _iconAnimationController.reset();
      _iconAnimationController.forward();
    }
  }

  void _onPageChanged(int index) {
    setState(() {
      _currentIndex = index;
    });
    
    // 播放图标动画
    _iconAnimationController.reset();
    _iconAnimationController.forward();
  }

  @override
  Widget build(BuildContext context) {
    // 显示加载指示器
    if (_isLoading) {
      return Scaffold(
        backgroundColor: AppTheme.scaffoldColor,
        body: const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primaryColor),
              ),
              SizedBox(height: 16),
              Text(
                '正在加载数据...',
                style: TextStyle(
                  fontSize: 16,
                  color: AppTheme.textSecondaryColor,
                ),
              ),
            ],
          ),
        ),
      );
    }

    return Scaffold(
      body: GestureDetector(
        // 确保页面级别的手势可以传递给PageView
        behavior: HitTestBehavior.translucent,
        child: PageView(
          controller: _pageController,
          onPageChanged: _onPageChanged,
          physics: const ClampingScrollPhysics(), // 使用Clamping物理效果确保滑动顺畅
        children: [
          TodayHomePage(
            tasks: _tasks,
            onTaskUpdate: _onTaskUpdate,
            onTaskDelete: _onTaskDelete,
          ),
          SchedulePage(
            tasks: _tasks,
            onTaskUpdate: _onTaskUpdate,
            onTaskDelete: _onTaskDelete,
          ),
          StatisticPage(
            tasks: _tasks,
          ),
          ProfilePage(
            tasks: _tasks,
          ),
        ],
      ),
      ),
      bottomNavigationBar: _buildCustomBottomNavBar(),
    );
  }

  Widget _buildCustomBottomNavBar() {
    return AnimatedBuilder(
      animation: _navAnimationController,
      builder: (context, child) {
        return SlideTransition(
          position: Tween<Offset>(
            begin: const Offset(0, 1),
            end: Offset.zero,
          ).animate(CurvedAnimation(
            parent: _navAnimationController,
            curve: Curves.easeOutCubic,
          )),
          child: Container(
            margin: const EdgeInsets.all(AppTheme.paddingL),
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.white,
                  Color(0xFFFAFBFF),
                ],
              ),
              borderRadius: BorderRadius.circular(AppTheme.radiusXL),
              boxShadow: [
                BoxShadow(
                  color: AppTheme.primaryColor.withOpacity(0.15),
                  blurRadius: 25,
                  offset: const Offset(0, 8),
                ),
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 15,
                  offset: const Offset(0, 4),
                ),
                BoxShadow(
                  color: Colors.white.withOpacity(0.9),
                  blurRadius: 20,
                  offset: const Offset(0, -5),
                ),
              ],
              border: Border.all(
                color: Colors.white.withOpacity(0.8),
                width: 1.5,
              ),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(AppTheme.radiusXL),
              child: BackdropFilter(
                filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                child: Container(
                  height: 65,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 6,
          ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      _buildNavItem(0, Icons.home_outlined, Icons.home_rounded, '今日'),
                      _buildNavItem(1, Icons.calendar_month_outlined, Icons.calendar_month_rounded, '日程'),
                      _buildNavItem(2, Icons.bar_chart_outlined, Icons.bar_chart_rounded, '统计'),
                      _buildNavItem(3, Icons.person_outline_rounded, Icons.person_rounded, '我的'),
                    ],
          ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildNavItem(int index, IconData unselectedIcon, IconData selectedIcon, String label) {
    final isSelected = _currentIndex == index;
    
    return Expanded(
      child: GestureDetector(
        onTap: () => _onTabTapped(index),
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOutCubic,
          padding: const EdgeInsets.symmetric(
            horizontal: 4,
            vertical: 4,
          ),
          decoration: BoxDecoration(
            gradient: isSelected ? AppTheme.primaryGradient : null,
            borderRadius: BorderRadius.circular(12),
            boxShadow: isSelected ? [
              BoxShadow(
                color: AppTheme.primaryColor.withOpacity(0.3),
                blurRadius: 6,
                offset: const Offset(0, 3),
              ),
            ] : null,
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 图标容器
              AnimatedSwitcher(
                duration: const Duration(milliseconds: 200),
                child: Container(
                  key: ValueKey('$index-$isSelected'),
                  child: AnimatedBuilder(
                    animation: _iconAnimationController,
                    builder: (context, child) {
                      return Transform.scale(
                        scale: isSelected 
                          ? 1.0 + (_iconAnimationController.value * 0.15)
                          : 1.0,
                        child: Icon(
                          isSelected ? selectedIcon : unselectedIcon,
                          size: 22,
                          color: isSelected ? Colors.white : AppTheme.textLightColor,
                        ),
                      );
                    },
                  ),
                ),
              ),
              const SizedBox(height: 3),
              
              // 标签文字
              AnimatedDefaultTextStyle(
                duration: const Duration(milliseconds: 200),
                style: TextStyle(
                  fontSize: 11,
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
                  color: isSelected ? Colors.white : AppTheme.textLightColor,
                ),
                child: Text(
                  label,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
          ),
        ],
          ),
        ),
      ),
    );
  }
}